#####
# Replication for: "Can Political Speech Foster Tolerance of Immigrants?" by Schleiter, Tavits, and Ward.
# Table S.17
#####

library(here)
library(data.table)
library(xtable)

if(!exists("pretest")){
  pretest <- fread(here("data", "pretest.csv"))
}


# Upper part of table (rating) --------------------------------------------

item_levels <- c("Not at all", "To some extent", "To a large extent")

# Create numeric versions of factor variables
pretest[ , CH_ch_num := as.numeric(factor(CH_ch, levels = item_levels))]
pretest[ , CH_nm_num := as.numeric(factor(CH_nm, levels = item_levels))]
pretest[ , CH_cs_num := as.numeric(factor(CH_cs, levels = item_levels))]

pretest[ , NM_ch_num := as.numeric(factor(NM_ch, levels = item_levels))]
pretest[ , NM_nm_num := as.numeric(factor(NM_nm, levels = item_levels))]
pretest[ , NM_cs_num := as.numeric(factor(NM_cs, levels = item_levels))]

pretest[ , CS_ch_num := as.numeric(factor(CS_ch, levels = item_levels))]
pretest[ , CS_nm_num := as.numeric(factor(CS_nm, levels = item_levels))]
pretest[ , CS_cs_num := as.numeric(factor(CS_cs, levels = item_levels))]

# rescale factors to the 0/.5/1 used in the paper
num_cols <- paste0(rep(c("NM", "CS", "CH"), each = 3), "_", rep(c("nm", "cs", "ch"), times = 3), "_num")
pretest[ , paste0(num_cols, "2") := lapply(.SD, function(x) (x-1)/2 ), .SDcols = num_cols]

# Output for the paper.
top_part <- pretest[ , lapply(.SD, mean, na.rm = T), .SDcols = paste0(num_cols, "2")]
top_part <- matrix(top_part, nrow = 3)
colnames(top_part) <- c("Norms", "Countering Stereotypes", "Common Humanity")
rownames(top_part) <- c("Tolerance", "Economy", "All Immigrants")

xtable(top_part, digits = 2)

# Lower part of table (Speaker belief) ------------------------------------

bottom_part <- cbind(
  pretest[!is.na(NM_pr) , table(NM_pr)/.N],
  pretest[!is.na(CS_pr) , table(CS_pr)/.N],
  pretest[!is.na(CH_pr) , table(CH_pr)/.N]
  )

# rearrange, clean up names
bottom_part <- bottom_part[c(2,3,1), ]
rownames(bottom_part) <- c("Democrats", "Republicans", "Both")

# xtable that is manipulated inside of latex
xtable(bottom_part * 100, digits = 1)


# Sample size -------------------------------------------------------------

# Norms
pretest[!is.na(NM_nm), .N]

# countering stereotypes 
pretest[!is.na(CS_cs), .N]

# common humanity
pretest[!is.na(CH_ch), .N]
